<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | [请手动修改文件描述]
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id$
// +-----------------------------------------------------------------------------------------------
namespace CMS;

class Model extends \think\Model {
    /**
     * 架构函数
     * @access public
     * @param array|object $data 数据
     */
    public function __construct($data = []) {
        if($data) {
            $this->_after_find($data);
        }
        parent::__construct($data);
    }
    protected function _after_find(&$result) {}

    /**
     * 获取数据列表，有缓存
     * @return array
     */
    public function lists($map = array()) {
        $keyname = $this->name;
        if(!$keyname) {
            return false;
        }
        $mk = $map?md5(serialize($map)):'all';
        $result = cache($keyname);
        if (!$result || !isset($result[$mk]) || !$result[$mk]) {
            $lists = $this->where($map)->select();
            if($lists) {
                if(is_object($lists)) {
                    $lists = $lists->toArray();
                }
                foreach($lists as $cat) {
                    if(is_object($cat)) {
                        $cat = $cat->toArray();
                    }
                    $result[$mk][$cat[$this->getPk()]] = $cat;
                }
            }
            cache($keyname, $result);
        }
        $result = $result[$mk];
        return $result;
    }

    /**
     * 清除已经缓存的列表
     *
     */
    public function clearList() {
        $keyname = $this->name;
        if(!$keyname) {
            return false;
        }
        cache($keyname, NULL);
    }

    /**
     * 将指定的表名替换成带前缀的表名（小写）
     * @access public
     * @param string $table 表名
     * @return string
     */
    public function parseTable($table = '') {
        $prefix = self::db()->getConfig('prefix');
        if (false !== strpos($table, '__')) {
            $table = preg_replace_callback("/__([A-Z0-9_-]+)__/sU", function ($match) use ($prefix) {
                return $prefix . strtolower($match[1]);
            }, $table);
        } else {
            $table = $prefix . \think\Loader::parseName($table);
        }
        return $table;
    }

    public function select($data = []) {
        if(method_exists($this, '_after_select')) {
            self::event('after_select', array($this, '_after_select'));
        }
        $model = false;
        foreach($data as $k=>$v) {
            $model = call_user_func(array($this, $k), $v);
        }
        if($model) {
            $resultSet = $model->select();
        } else {
            $resultSet = parent::select();
        }
        $this->trigger('after_select', $resultSet);
        return $resultSet;
    }


    protected static function init() {
        self::event('after_delete', function($model){
            $model->clearList();
        });
        self::event('after_write', function($model){
            $model->clearList();
        });
    }

    /**
     * 获取出错的信息
     * 没办法知道现在就是一定是出错了，这里只是尽可能的取到错误信息
     * {@inheritDoc}
     * @see \think\Model::getError()
     */
    public function getError(){
        if(!$this->error) {
            $this->error = '数据库查询出错：'.\think\Db::connect()->getError();
        }
        return $this->error;
    }
}
